const stringifyUrl = obj => {
  const url = Object.keys(obj)
    .reduce((target, curr) => {
      if (curr !== 'url') {
        target += `${curr}=${obj[curr]}&`
      }
      return target
    }, obj.url + '?')
    .slice(0, -1)
  return url
}

export default async function handler(req, res) {
  // 获取XHR请求中的M3U8或TS地址
  const url = stringifyUrl(req.query)
  if (!url.includes('.m3u8') && !url.includes('.ts')) {
    res.status(200).json({ msg: 'no m3u8 or ts' })
    return
  }

  const request = url.includes('https') ? require('https') : require('http')

  // 创建请求
  const streamReq = request.get(url)

  //监听错误事件
  streamReq.on('error', function (error) {
    res.status(500).json({ message: 'Error fetching and streaming data', error })
    return
  })

  streamReq.on('response', async stream => {
    // 处理302问题。
    if (stream.statusCode == 302) {
      res.writeHead(302, {
        'Location': '/api/loadm3u8?url=' + stream.headers.location.replace('?','&')
      })
    } else {
      res.writeHead(200, { 'Content-Type': stream.headers['content-type'] || 'application/octet-stream' })
    }
    stream.on('data', data => {
      res.write(data)
    })
    // 监听数据流结束事件，结束响应
    stream.on('end', () => {
      res.end()
    })
  })
}
